文章目录
  1. 1. Question:ZigZag Conversion
  2. 2. SourceCode:
    1. 2.1. s1
    2. 2.2. s2

Question:ZigZag Conversion

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of 

rows like this: (you may want to display this pattern in a fixed font for better

legibility)

P   A   H   N
A P L S I I G
Y   I   R

And then read line by line: "PAHNAPLSIIGYIR"

Write the code that will take a string and make this conversion given a number of rows:

string convert(string text, int nRows);

convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".

SourceCode:

s1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
//笔者提交版本;耗时:6ms;
public class Solution {
public String convert(String s, int numRows) {
if(null == s){return "";}
int len = s.length();
//边界控制要仔细啊,numRows <=1
if(numRows >= len||numRows <=1){return s;}
StringBuilder result = new StringBuilder(len);
int step = numRows - 2 + numRows;
int lastLineNum = numRows -1 ;
for(int i= 0 ; i< numRows ;i++){
//第一行和最后一行
if(i==0 || i == lastLineNum){
int j = i;
while(j<len){
result.append(s.charAt(j));
j += step;
}
}
//中间行处理
else{
int tmpStep = (lastLineNum-i)*2;
//成对处理
int j = i;
int k = j + tmpStep;
while(j<len){
result.append(s.charAt(j));
j += step;
if(k<len){
result.append(s.charAt(k));
k += step;
}
}
}
}
return result.toString();
}
}

s2

1
2
//该版本参考了Discuss,还没看Discuss;耗时:ms;
//待写
文章目录
  1. 1. Question:ZigZag Conversion
  2. 2. SourceCode:
    1. 2.1. s1
    2. 2.2. s2